import 'package:flutter/material.dart';
import 'result_screen.dart';
import 'question_generator.dart';
import 'audio_feedback.dart';

class QuestionScreen extends StatefulWidget {
  final String category;
  final int difficulty;

  const QuestionScreen({super.key, required this.category, required this.difficulty});

  @override
  State<QuestionScreen> createState() => _QuestionScreenState();
}

class _QuestionScreenState extends State<QuestionScreen> {
  late Map<String, dynamic> currentQuestion;
  late AudioFeedback audioFeedback;
  int score = 0;
  int questionCount = 0;

  @override
  void initState() {
    super.initState();
    audioFeedback = AudioFeedback();
    _generateQuestion();
  }

  @override
  void dispose() {
    audioFeedback.dispose();
    super.dispose();
  }

  void _generateQuestion() {
    setState(() {
      currentQuestion = QuestionGenerator().generateQuestion(widget.category, widget.difficulty);
      questionCount++;
    });
  }

  void _checkAnswer(int selectedOption) {
    final correctAnswer = currentQuestion['answer'] as int;
    if (selectedOption == correctAnswer) {
      setState(() {
        score++;
      });
      audioFeedback.playFeedback(FeedbackType.correct);
      // 添加奖励逻辑
    } else {
      audioFeedback.playFeedback(FeedbackType.incorrect);
    }
    
    // 进入下一题或显示结果
    if (questionCount < 10) { // 每关10题
      Future.delayed(const Duration(seconds: 1), _generateQuestion);
    } else {
      _showResult();
    }
  }

  void _showResult() {
    // 显示得分和奖励界面
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => ResultScreen(score: score)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('${widget.category} 关卡 ${widget.difficulty}')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              currentQuestion['question'] as String,
              style: const TextStyle(fontSize: 48),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 32),
            Wrap(
              spacing: 16,
              runSpacing: 16,
              children: (currentQuestion['options'] as List<int>)
                  .map((option) => _buildAnswerButton(option))
                  .toList(),
            ),
            const SizedBox(height: 16),
            Text('得分: $score'),
          ],
        ),
      ),
    );
  }

  Widget _buildAnswerButton(int option) {
    return ElevatedButton(
      onPressed: () => _checkAnswer(option),
      style: ElevatedButton.styleFrom(
        fixedSize: const Size(80, 80),
        textStyle: const TextStyle(fontSize: 24),
      ),
      child: Text('$option'),
    );
  }
}